package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.fasterxml.jackson.databind.JsonNode;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.FlowReNodeAuthVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowReNodeAuthRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.entities.FlowReNodeAuth;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.mapper.FlowReNodeAuthDAO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class FlowReNodeAuthRepositoryImpl implements FlowReNodeAuthRepository {

    @Autowired
    private FlowReNodeAuthDAO nodeAuthDAO;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveNodeAuth(String deployId, String nodeCode, JsonNode nodeAuthProperties) {
        List<FlowReNodeAuth> nodeAuthList = new ArrayList<>();
        Iterator<Map.Entry<String, JsonNode>> fields = nodeAuthProperties.fields();
        Date concurrentDate = new Date();
        while (fields.hasNext()) {
            Map.Entry<String, JsonNode> entry = fields.next();
            FlowReNodeAuth nodeAuth = new FlowReNodeAuth();
            nodeAuth.setNodeCode(nodeCode);
            nodeAuth.setDepolyId(deployId);
            nodeAuth.setAuthName(entry.getKey());
            JsonNode value = entry.getValue();
            if (!value.isNull()) {
                nodeAuth.setAuthContent(value.toString());
                if (value.isObject()) {
                    nodeAuth.setAuthSwitch(value.get("switch").asBoolean());
                } else if (value.isArray()) {
                    nodeAuth.setAuthSwitch(true);
                } else {
                    nodeAuth.setAuthSwitch(Boolean.valueOf(value.toString()));
                }
            }
            nodeAuth.setCreateTime(concurrentDate);
            nodeAuth.setUpdateTime(concurrentDate);
            nodeAuthList.add(nodeAuth);
        }
        nodeAuthDAO.batchInsert(nodeAuthList);
        return 0;
    }

    @Override
    public List<FlowReNodeAuthVo> listNodeAuthByProcdefIdAndNodeCode(String procdefId, String nodeCode) {
        return nodeAuthDAO.selectByProcdefIdAndNodeCode(procdefId, nodeCode).stream().map(this::convert).collect(Collectors.toList());
    }

    private FlowReNodeAuthVo convert(FlowReNodeAuth entity) {
        if (Objects.isNull(entity)) {
            return null;
        }

        FlowReNodeAuthVo result = new FlowReNodeAuthVo();
        BeanUtils.copyProperties(entity, result);
        return result;
    }
}
